<?php


namespace api\applets\controller;


use cmf\controller\RestBaseController;
use think\Db;

class UsersController extends RestBaseController
{
    public function login()
    {
        $requst = $this->request;
        $APPID = "wxd5861ea6d3afeef2";
        $AppSecret = "64e16db31cd072e1cb3e286590f34e6f";
        if (empty($requst->post('code')) || empty($requst->post('signature')) || empty($requst->post('rawData')) || empty($requst->post('encryptedData')) || empty($requst->post('iv'))) {
            $this->error(0, '参数缺失');
        }
        $code = trim($requst->param('code'));
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $APPID . '&secret=' . $AppSecret . '&js_code=' . $code . '&grant_type=authorization_code';
        $arr = $this->vegt($url);
        $arr = json_decode($arr, true);
        if (empty($arr) || empty($arr['openid']) || empty($arr['session_key'])) {
            $this->error(0, '请求微信接口失败,appid或私钥不匹配！');
        }
//        print_r($arr) ;die;
//        if (isset($arr['errcode'])){
//            $this->error("请求微信接口失败！");
//        }
        $openid = $arr['openid'];
        $shareuser = $requst->param('shareuser');
        $session_key = $arr['session_key'];
        // 数字签名校验
        $signature = $requst->post('signature');
        $rawData = $requst->post('rawData');
        $signature2 = sha1($rawData . $session_key);
        if ($signature != $signature2) {
            $this->error("数字签名失败！");
        }
        // 获取信息，对接口进行解密
//        Vendor("WXBiz.wxBizDataCrypt");

        $encryptedData = $requst->post('encryptedData');
        $iv = $requst->post('iv');
        require_once dirname(dirname(__DIR__)) . '/applets/WXBiz/wxBizDataCrypt.php';
//        Vendor("WXBiz.wxBizDataCrypt");
        $pc = new \WXBizDataCrypt($APPID, $session_key);
        $errCode = $pc->decryptData($encryptedData, $iv, $data);
        if ($errCode != 0) {
            $this->error("解密数据失败");
        } else {
            $data = json_decode($data, true);
            session('myinfo', $data);
            $save['openID'] = $data['openId'];
            $save['nickname'] = $this->removeEmoji($data['nickName']);
            $save['sex'] = $data['gender'];
            $save['city'] = $data['city'];
            $save['province'] = $data['province'];
            $save['add_time'] = time();
//            $save['avatar'] = $data['avatarUrl'];
//            $save['uid'] = $shareuser;
            //$save['session_key'] = $session_key;
            $map['openID'] = $data['openId'];
            !empty($data['unionId']) && $save['unionId'] = $data['unionId'];
            //生成第三方3rd_session
            $session3rd = null;
            $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
            $max = strlen($strPol) - 1;//字符串长度
            for ($i = 0; $i < 16; $i++) {
                $session3rd .= $strPol[rand(0, $max)];//生成16位字节码
            }
            $save['access_token'] = 'BKS' . date('YmdHis') . 'HS' . $session3rd;
            //创建返回信息
            $rtn['token'] = $session3rd;
            //存入数据库
            $res = Db::name("aws_users_weixin")->where($map)->find();//判断是否是新用户，新用户的话存入父id
            if (empty($res)) {
                $db = Db::name("aws_users_weixin")->insert($save);
                if ($db !== false) {
                    $res1 = Db::name("aws_users_weixin")->where($map)->find();
                    $rtn['userid'] = $res1['id'];
                    $rtn['session_key'] = $session_key;
                    $rtn['access_token'] = $res1['access_token'];
                    $rtn['openID'] = $res1['openID'];
                    $this->success("T", $rtn);
                } else {
                    $this->error("F", "用户登录失败");
                }
            } else {
                $rtn['userid'] = $res['id'];
                $rtn['session_key'] = $session_key;
                $rtn['access_token'] = $res['access_token'];
                $rtn['openID'] = $res['openID'];
                $this->success("T", $rtn);
            }
        }
    }

    public function vegt($url)
    {
        $info = curl_init();
        curl_setopt($info, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($info, CURLOPT_HEADER, 0);
        curl_setopt($info, CURLOPT_NOBODY, 0);
        curl_setopt($info, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($info, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($info, CURLOPT_URL, $url);
        $output = curl_exec($info);
        curl_close($info);
        return $output;
    }

    /**
     * 获取手机号
     */
    public function getPhone()
    {
        $request = $this->request;
        $appId = "wxd5861ea6d3afeef2";
        $encryptedData = $request->param("encryptedData");
        $iv= $request->param("iv");
        $sessionKey = $request->param("session_key");
        require_once dirname(dirname(__DIR__)) . '/applets/WXBiz/wxBizDataCrypt.php';
        $pc = new \WXBizDataCrypt($appId, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data);
        if ($errCode != 0) {
            $this->error("解密数据失败");
        } else {
            $data = json_decode($data, true);
            $this->success("成功", $data);
        }

    }

    public function removeEmoji($clean_text)
    {
        // 方法1：只取合法字符
        preg_match_all("/[\x{4e00}-\x{9fa5}|0-9|a-z|A-Z|_]/u", $clean_text, $matches);
        $clean_text = isset($matches[0]) ? implode('', $matches[0]) : '';


        // 方法2：去除表情字符，但测试过程中发现无法出去“国旗”表情
        // Match Emoticons
        $regexEmoticons = '/[\x{1F600}-\x{1F64F}]/u';
        $clean_text = preg_replace($regexEmoticons, '', $clean_text);

        // Match Miscellaneous Symbols and Pictographs
        $regexSymbols = '/[\x{1F300}-\x{1F5FF}]/u';
        $clean_text = preg_replace($regexSymbols, '', $clean_text);

        // Match Transport And Map Symbols
        $regexTransport = '/[\x{1F680}-\x{1F6FF}]/u';
        $clean_text = preg_replace($regexTransport, '', $clean_text);

        // Match Miscellaneous Symbols
        $regexMisc = '/[\x{2600}-\x{26FF}]/u';
        $clean_text = preg_replace($regexMisc, '', $clean_text);

        // Match Dingbats
        $regexDingbats = '/[\x{2700}-\x{27BF}]/u';
        $clean_text = preg_replace($regexDingbats, '', $clean_text);

        return $clean_text;
    }

}